/*
 * Daemon.java
 *
 * Created on June 30, 2007, 12:31 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.xeerkat.xmpp.server.tools;

import java.io.File;
import java.net.URI;
import java.util.logging.Level;

/**
 *
 * @author alex
 */
public class Daemon
{

   Main main;
   
   /** Creates a new instance of Daemon */
   public Daemon()
   {
   }
   
   public void init(String[] args) {
      // Here open the configuration files, create the trace file, create the ServerSockets, the Threads
      int argIndex = 0;
      Level logLevel = Level.INFO;
      while (argIndex<args.length && args[argIndex].charAt(0)=='-') {
         String name = args[argIndex].substring(1);
         argIndex++;
         if (argIndex==args.length) {
            throw new RuntimeException("The argument "+args[argIndex]+" requires an argument.");
         }
         if (name.equals("l") || name.equals("-level")) {
            if (args[argIndex].equals("info")) {
               logLevel = Level.INFO;
            } else if (args[argIndex].equals("fine")) {
               logLevel = Level.FINE;
            } else if (args[argIndex].equals("finer")) {
               logLevel = Level.FINER;
            } else if (args[argIndex].equals("finest")) {
               logLevel = Level.FINEST;
            } else if (args[argIndex].equals("config")) {
               logLevel = Level.CONFIG;
            }
         }
         argIndex++;
      }
      int argCount = args.length-argIndex;
      
      if (argCount!=1) {
         throw new RuntimeException("The minimum number of argument is 1 (the configuration file).");
      }
      URI location = args[argIndex].charAt(0)=='!' ? URI.create(args[argIndex].substring(1)) : (new File(args[argIndex])).toURI();
      try {
         main = new Main(location);
         main.init();
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
   
   public void start() {
      // Start the Thread, accept incomming connections
      try {
         main.run();
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
   
   public void stop() {
      // Inform the Thread to live the run(), close the ServerSockets
      try {
        main.stop();
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
   
   public void destroy() {
      // Destroy any object created in init()
      main = null;
   }

}
